import React,{useState,useEffect} from 'react';
import '../../styles/zheng/DataO.scss'
import { NavLink, useNavigate } from 'react-router-dom';
import {Input,Button,Table,Radio,Switch,message,Modal} from 'antd'
import {ExclamationCircleFilled} from '@ant-design/icons'
import {getOrglist,deleteOrg,patchOrg} from '../../api/zheng/index'
interface Props{

}

const { Search } = Input;
const { confirm } = Modal;
function DataOrganization(props:Props) {
    const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');
    var [truelist,setTruelist] = useState([])
    var [list,setList] = useState([])
    var [key,setKey] = useState('')
    var navigate = useNavigate()
    var [loading,setLoading] = useState(false)
    var [pagination,setPagination] = useState({current:1,pageSize:5,total:100})
    const [messageApi, contextHolder] = message.useMessage()
    // 挂载阶段
    useEffect(()=>{
        getOrglist().then(res=>{
            console.log(res.data);
            setList(res.data)
            setLoading(false)
            setPagination({
                ...pagination,total:res.data.length
            })
        })
    },[])
    // 点击搜索的时候
    const onSearch = (value:string)=>{
        getOrglist().then(res=>{
           var arr = res.data.filter((item:any)=>{
            return item.name.indexOf(value)!= -1
           })
           setList(arr)
        })
    }
     // 多选
     const rowSelection = {
        onChange: (selectedRowKeys:any, selectedRows:any)=> {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
          setTruelist(selectedRowKeys)
        }
      }

    // 点击删除
    const showConfirm=(id:any)=>{
        confirm({
            title: '删除确认',
            icon: <ExclamationCircleFilled />,
            content: '机构信息删除后无法恢复，确定删除吗？',
            okText:"确认",
            cancelText:"取消",
            onOk() {
                deleteOrg({id}).then((res:any)=>{
                    if(res.status == 200){
                        messageApi.open({
                            type: 'success',
                            content: '删除成功',
                          });
                          setTimeout(()=>{
                            navigate(0)
                          },500)
                    }
                }) 
            },
            onCancel() {
              console.log('已取消');
              
            },
          });
    }
    // 改变状态
    const onChange=(checked:any,item:any)=>{
        patchOrg({...item,states:checked}).then(res=>{
            console.log(res);
        })
    }
    // 表格
    const columns = [
        {
            title: '编号', //表格头的标题
            dataIndex: 'id', //数据索引，决定通过哪个属性名（字段名）获取数据
            key: 'id', 
        },
        {
            title: '机构图片',
            dataIndex: 'img',
            key: 'img',
            render:(_:any,record:any)=>{
                return (
                    <img src={record.img} alt={record.img} />
                )
            }
        },
        {
            title: '机构名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '负责人姓名',
            dataIndex: 'leader',
            key: 'leader',
        },
        {
            title: '电话',
            dataIndex: 'phone',
            key: 'phone',
        },
        {
            title: '机构地址',
            dataIndex: 'address',
            key: 'address',
        },
        {
            title: '状态',
            dataIndex: 'states',
            key: 'states',
            render:(_:any,record:any)=>{
                return(
                    <Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked={record.states} onChange={(checked,item)=>{onChange(checked,record)}}/>
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'handle',
            key: 'handle',
            render:(_:any,record:any)=>{ //动态渲染当前列的数据，和dataIndex有冲突
               return(
                <>
                   <NavLink className='pen' to='/index/info-organization-handleorg' state={record}>编辑</NavLink>
                   <a className='delete' onClick={(id)=>{showConfirm(record.id)}}>删除</a>
                </>
               )
            }
        },
    ]
    // 点击新增
    const addOrg = ()=>{
        navigate('/index/info-organization-addorg')
    }
    // 分页发生改变后执行
    const handleChange = (pagi:any) =>{
        setPagination(pagi) //更新页码
        setLoading(true)
        // 请求新的页码对应的数据
        getOrglist().then(res=>{
            if(res.status ==200){
                setLoading(false)
                setPagination({
                    ...pagi,total:res.data.length
                })
                
            }
        })
    }
    return (
        <div className='data-organization'>
            <div className="title">
                <div className='leftborder'></div>
                <h3>机构管理</h3>
            </div>
            <div className="inputbox">
                <Search placeholder="请输入机构名称关键字"  onSearch={onSearch} style={{ width: 300 }} />
            <div className="btnbox">
                <Button type="primary" onClick={addOrg}>新增机构</Button>
                <Button>导出</Button>
            </div>
            </div>
            <Radio.Group
                    onChange={({ target: { value } }) => {
                        setSelectionType(value);
                    }}
                    value={selectionType}
                >
                </Radio.Group>
            {/* <Table columns={columns} dataSource={list} pagination={pagination} onChange={(pagi)=>{handleChange(pagi)}} loading={loading}/> */}
            <Table 
             rowSelection={{
                type: selectionType,
                ...rowSelection,
            }}
            pagination={pagination}
            onChange={(pagi)=>{handleChange(pagi)}}
            loading={loading}
            dataSource={list}
            columns={columns} />
        </div>
    );
}

export default DataOrganization;